import { getMenuListFromCurrentUser } from "@/api/permission"
import { traverseRoutes } from "@/utils/route"
import { constantRoutes } from '@/router'

const state = {
    routes: [],
    baseMenus: []
}

const mutations = {
    SET_ROUTES: (state, routes) => {
        state.routes = constantRoutes.concat(routes)
    },
    SET_BASE_MENUS: (state, menus) => {
        state.baseMenus = menus
    }
}

const actions = {
    getSideMenus({ commit, state }) {
        return new Promise((resolve, reject) => {
            //获取菜单列表
            getMenuListFromCurrentUser()
                .then(
                    response => {
                        const menus = response
                        commit('SET_BASE_MENUS', menus)
                        let remoteroutes = traverseRoutes(menus)
                        commit('SET_ROUTES', remoteroutes)
                        resolve(remoteroutes)
                    }
                )
                .catch(
                    error => {
                        reject(error)
                    }
                )
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}